<?php

namespace app\api\controller;

use app\common\lib\ChatGpt;
use app\common\lib\Sensitive;
use app\common\model\MemberPointsLog;
use hg\apidoc\annotation as Apidoc;
use hg\apidoc\annotation\Param;
use hg\apidoc\annotation\Query;
use hg\apidoc\annotation\Returned;
use hg\apidoc\annotation\Header;
use app\BaseController;
use think\facade\View;
use think\facade\Db;
use think\response\Json;

/**
 * 文案创作
 *
 * api-Copywriting
 *
 * @Apidoc\Title("文案创作")
 * @Apidoc\Group("api")
 */
class Copywriting extends Auth
{
    /**
     * getList
     * @Apidoc\Title("获取产品列表")
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList()
    {
        $classes = \app\common\model\CopywritingClassification::order('sort', 'asc')->select();
        $classes = $classes->toArray();
        foreach ($classes as $index => $class) {
            $classes[$index]['active'] = false;
            $classes[$index]['lists'] = \app\common\model\Copywriting::order('sort', 'asc')
                ->where('copywriting_classification_id', $class['id'])
                ->append(['active'])
                ->withAttr('active', function ($value, $data) {
                    return false;
                })
                ->select();
        }
        return success('', $classes);

    }


    /**
     * 获取生成语言
     * @Apidoc\Title("获取生成语言")
     * getLanguage
     */
    public function getLanguage()
    {
        $language = config('article_creation.language');
        $arr = explode("\r\n", trim($language));
        return success('', $arr);
    }


    /**
     * @Apidoc\Title("获取产品相关信息")
     * getDat
     */
    public function getData()
    {
        $id = input('id');
        $copywriting = \app\common\model\Copywriting::field(['custom_fields', 'name', 'picture', 'is_language', 'is_tone','describe'])->find($id);
        $custom_fields = $copywriting['custom_fields'];
        $fields = explode("\r\n", $custom_fields);
        $user_fields = [];
        foreach ($fields as $field) {
            if ($field) {
                $user_fields[] = explode("__", $field);
            }
        }
        $user_data = \app\common\model\CopywritingMember::order('id', 'desc')
            ->where('copywriting_id', $id)
            ->where('member_id', $this->request->uid)->select();
        $tones = explode("\r\n", trim(config('article_creation.creative_tone')));
        return success('', [
            'data' => $copywriting,
            'fields' => $user_fields,
            'user_data' => $user_data,
            'tones' => $tones
        ]);

    }


    /**
     * getAccess
     * @Apidoc\Title("能否生成")
     */
    public function getAccess()
    {
        /******************言论审查开始***********************************/
        //数据检验开始，这里审查用户的言论是否符合国家法律规定，这里一定要加上++++++++++++++++++++++++++++++++++++++++++++++++++++++
        $TextModeration=new \app\api\service\TextModerationService();
        if (!$TextModeration->check(json_encode($this->request->param(),JSON_UNESCAPED_UNICODE))) {
            return error($TextModeration->msg);
        }
        /*****************言论审查结束了**********************************/
        $data = input();

        $generated_quantity = input('generated_quantity', '', 'intval');

        // 验证 是否为空 和是否有敏感词
        $copywriting_id = $data['copywriting_id'];
        $copywriting = \app\common\model\Copywriting::field(['custom_fields', 'name', 'picture', 'is_language', 'is_tone'])->find($copywriting_id);
        $custom_fields = $copywriting['custom_fields'];
        $fields = explode("\r\n", $custom_fields);
        $user_fields = [];
        foreach ($fields as $field) {
            if ($field) {
                $user_fields[] = explode("__", $field);
            }
        }
        $rules = [];
        foreach ($user_fields as $field) {
            $rules[$field[0] . '|' . $field[1] ] = 'require';
        }
        validate($rules)->check($data);
        foreach ($user_fields as $field) {
            $key_word = $data[$field[0]];
            $res = Sensitive::has($key_word);
            if($res) {
                //return error( $field[1] . '不能包含敏感词：'. Sensitive::get($key_word));
                return error('不能包含敏感词');
            }
        }


        // 验证积分
        $point_per_title = config('article_creation.points_per_creation');
        if ($point_per_title) {
            $member = \app\common\model\Member::find($this->request->uid);
            $member_point = $member['point_num'];
            if ($member_point < $point_per_title * $generated_quantity) {
                return error('积分不足, 请充值积分！', ['action' => 'recharge']);
            } else {
                $member->point_num = $member_point - $point_per_title * $generated_quantity;
                $member->save();

                MemberPointsLog::create([
                    'member_id' => $member->id,
                    'num' => -1 * $point_per_title * $generated_quantity,
                    'end_num' => $member_point - $point_per_title * $generated_quantity,
                    'remarks' => "文案创作"
                ]);
            }
        }


        $random_key = uniqid();
        cache($random_key, $generated_quantity, ['expire' => 100]);
        cache($random_key . '_content', $data, ['expire' => 100]);
        return success('', ['key' => $random_key, 'form' => $data, 'num'=>$generated_quantity]);
    }



}
